import { ReactComponent as AssistantIcon } from '@/assets/svg/assistant.svg';
import { MessageType } from '@/constants/chat';
import { useTranslate } from '@/hooks/common-hooks';
import { useSelectFileThumbnails } from '@/hooks/knowledge-hooks';
import { IReference, Message } from '@/interfaces/database/chat';
import { IChunk } from '@/interfaces/database/knowledge';
import MarkdownContent from '@/pages/chat/markdown-content';
import { getExtension } from '@/utils/document-util';
import { Avatar, Button, Flex, List, Tooltip, message } from 'antd';
import classNames from 'classnames';
import { useCallback, useMemo } from 'react';
import NewDocumentLink from '../new-document-link';
import styles from './index.less';

// Inline SVG for copy icon
const CopyIcon = () => (
  <svg
    width="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path
      d="M17 3H7C5.34315 3 4 4.34315 4 6V16C4 17.6569 5.34315 19 7 19H17C18.6569 19 20 17.6569 20 16V6C20 4.34315 18.6569 3 17 3ZM17 1C19.2091 1 21 2.79086 21 5V16C21 18.2091 19.2091 20 17 20H7C4.79086 20 3 18.2091 3 16V5C3 2.79086 4.79086 1 7 1H17ZM16 8H8C7.44772 8 7 8.44772 7 9C7 9.55228 7.44772 10 8 10H16C16.5523 10 17 9.55228 17 9C17 8.44772 16.5523 8 16 8ZM16 12H8C7.44772 12 7 12.4477 7 13C7 13.5523 7.44772 14 8 14H16C16.5523 14 17 13.5523 17 13C17 12.4477 16.5523 12 16 12ZM20 22H8C7.44772 22 7 21.5523 7 21V9C7 8.44772 7.44772 8 8 8H20C20.5523 8 21 8.44772 21 9V21C21 21.5523 20.5523 22 20 22Z"
      fill="#1890FF"
    />
  </svg>
);

interface IProps {
  item: Message;
  reference: IReference;
  loading?: boolean;
  nickname?: string;
  avatar?: string;
  clickDocumentButton?: (documentId: string, chunk: IChunk) => void;
}

const MessageItem = ({
  item,
  reference,
  loading = false,
  avatar = '',
  nickname = '',
  clickDocumentButton,
}: IProps) => {
  const isAssistant = item.role === MessageType.Assistant;
  const { t } = useTranslate('chat');
  const fileThumbnails = useSelectFileThumbnails();

  const referenceDocumentList = useMemo(() => {
    return reference?.doc_aggs ?? [];
  }, [reference?.doc_aggs]);

  const content = useMemo(() => {
    let text = item.content;
    if (text === '') {
      text = t('searching');
    }
    return loading ? text?.concat('~~2$$') : text;
  }, [item.content, loading, t]);

  // Handle copying content with success message
  const handleCopyContent = useCallback(() => {
    navigator.clipboard
      .writeText(content)
      .then(() => {
        message.success('内容已复制到剪贴板');
      })
      .catch((err) => {
        message.error('复制失败，请重试');
        console.error('Failed to copy content: ', err);
      });
  }, [content]);

  return (
    <div
      className={classNames(styles.messageItem, {
        [styles.messageItemLeft]: item.role === MessageType.Assistant,
        [styles.messageItemRight]: item.role === MessageType.User,
      })}
    >
      <section
        className={classNames(styles.messageItemSection, {
          [styles.messageItemSectionLeft]: item.role === MessageType.Assistant,
          [styles.messageItemSectionRight]: item.role === MessageType.User,
        })}
      >
        <div
          className={classNames(styles.messageItemContent, {
            [styles.messageItemContentReverse]: item.role === MessageType.User,
          })}
        >
          {item.role === MessageType.User ? (
            <Avatar
              size={40}
              src={
                avatar ??
                'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
              }
            />
          ) : (
            <AssistantIcon />
          )}
          <Flex vertical gap={8} flex={1}>
            <b>{isAssistant ? '' : nickname}</b>
            <div
              className={
                isAssistant ? styles.messageText : styles.messageUserText
              }
            >
              <MarkdownContent
                content={content}
                reference={reference}
                clickDocumentButton={clickDocumentButton}
              />
            </div>
            {isAssistant && referenceDocumentList.length > 0 && (
              <List
                bordered
                dataSource={referenceDocumentList}
                renderItem={(item) => {
                  const fileThumbnail = fileThumbnails[item.doc_id];
                  const fileExtension = getExtension(item.doc_name);
                  return (
                    <List.Item>
                      <Flex gap={'small'} align="center">
                        {fileThumbnail ? (
                          <img
                            src={fileThumbnail}
                            className={styles.thumbnailImg}
                          />
                        ) : (
                          <svg
                            width="24"
                            height="24"
                            viewBox="0 0 24 24"
                            fill="none"
                            xmlns="http://www.w3.org/2000/svg"
                          >
                            <path d={`M...Z`} fill="#000000" />{' '}
                            {/* 根据需要调整路径 */}
                          </svg>
                        )}
                        <NewDocumentLink
                          documentId={item.doc_id}
                          documentName={item.doc_name}
                          prefix="document"
                        >
                          {item.doc_name}
                        </NewDocumentLink>
                      </Flex>
                    </List.Item>
                  );
                }}
              />
            )}
            <Flex justify="end" style={{ marginTop: 8 }}>
              <Tooltip title="复制">
                <Button
                  icon={<CopyIcon />}
                  onClick={handleCopyContent}
                  className={styles.copyButton}
                  type="text" // 使用文本按钮样式，使其更轻量
                />
              </Tooltip>
            </Flex>
          </Flex>
        </div>
      </section>
    </div>
  );
};

export default MessageItem;
